import requests
import json
import time
import hmac
import hashlib
import base64
import urllib.parse
from datetime import datetime

# 机器人QFinanceGridModel_RT01
webhook = "https://oapi.dingtalk.com/robot/send?access_token=8147acde89e562d01ef4d3ee6a88e28e81367bd3f65938d62f86aaf589bdf8ed"
secret = "SEC64591e43b73770bf99d288e6fa4590fc6756946118189793b657aeef6b906e43"


def send_dingtalk_message(content, at_mobiles=None):
    # 1. 生成签名（钉钉要求）
    timestamp = str(round(time.time() * 1000))
    secret_enc = secret.encode("utf-8")
    string_to_sign = f"{timestamp}\n{secret}"
    string_to_sign_enc = string_to_sign.encode("utf-8")
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

    # 2. 构造请求（含签名）
    url = f"{webhook}&timestamp={timestamp}&sign={sign}"
    headers = {"Content-Type": "application/json"}
    data = {
        "msgtype": "text",
        "text": {"content": f"[爬虫监控] {datetime.now().strftime('%Y-%m-%d %H:%M')}\n{content}"},
        "at": {"atMobiles": at_mobiles or [], "isAtAll": False}  # 支持@指定手机号
    }

    # 3. 发送消息
    response = requests.post(url, headers=headers, data=json.dumps(data))
    
    print("发送成功" if response.json().get("errcode") == 0 else "发送失败")


# 测试发送
if __name__ == "__main__":
    send_dingtalk_message("测试数据：今日爬取商品42件", at_mobiles=["13800001111"])
